import {
  getImage,
  getPage,
  getTabbar
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
const app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  //console.log(headerInfo)
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getImage: getImage,
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    navbar: {},
    window: {},
    city: "",
    goodsList: [],
    goodsListPage: 1,
    goodsListPages: 0,
    loadmore: true,
    loaddone: false,
    rec_list: [],
    rec_pageindex: 1,
    rec_pages: 0,
    rec_loadmore: true,
    rec_loaddone: false,
    tipTopStyle: tipTopStyle,
    leftStyle: leftStyle,
    topStyle: topStyle,
    value1: 0,
    option1: [{
        text: '智能排序',
        value: 0
      },
      {
        text: '离我最近',
        value: 1
      },
      {
        text: '评分从高到低',
        value: 2
      },
    ],
    s_province: 0,
    s_city: 0,
    regionInfo: [],
    province: [],
    cities: [],
    abnor: false,
    zonelist: [],
    zoneid: 0,
    navbarInitHeight: 0, //导航栏高度
    stkInitHeight: 0, //吸顶盒子高度
    isFixedTop: false, //是否固定顶部
  },
  /**
   * 获取地区
   */
  getRegionInfo() {
    return new Promise((resolve) => {
      storage.get('regionInfo').then((res) => {
        this.setData({
          regionInfo: res,
          pickerArea: false
        });
        console.log("getRegionInfo----------", this.data.regionInfo)
        resolve(res);
      }).catch((res) => {
        http.get(api.default, {
          data: {
            action: 'district'
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          this.setData({
            regionInfo: data,
            pickerArea: false
          });
          storage.set('regionInfo', data);
          resolve(data);
        });
      });
    });
  },
  formatArea() {
    const {
      regionInfo,
      province
    } = this.data;

    regionInfo.forEach((item, index) => {
      province.push({
        text: item.name,
        value: item.id
      })
    });
    var cities = regionInfo[0].list;
    var city = [{
      text: "请选择",
      value: 0
    }];
    cities.forEach((c, i) => {
      city.push({
        text: c.name,
        value: c.id
      })
    });
    this.setData({
      province,
      s_province: province[0].value,
      cities: city
    });
  },
  zoneSubmit(e) {
    var zoneid = this.data.zoneid;
    var cityid = this.data.s_city;
    var provinceid = this.data.s_province;
    const {
      regionInfo
    } = this.data;
    if (zoneid > 0 || cityid > 0 || provinceid > 0) {
      app.globalData.zoneid = zoneid ? zoneid : (cityid ? cityid : provinceid);
      //获取设置城市id
      http.post(api.default, {
        data: {
          action: 'getregioninfo',
          id: app.globalData.zoneid
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        if (data != null) {
          app.globalData.zone = data;
          this.setData({
            islocation: false,
            city: app.globalData.zone.shortname,
          });
          this.getProductsInfo((res) => {
            this.setData({
              goodsList: res.list,
              loadmore: false,
            });
            if (this.data.loaddone || res.list.length == 0) {
              this.setData({
                rec_pageindex: 1,
                rec_pages: 0
              });
              this.getRecShopList((res1) => {
                this.setData({
                  rec_list: res1.list,
                  rec_loadmore: false,
                });
              });
            }
          });
        }
      });
    } else {
      $toast('请选择城市');
    }
  },
  province_change(e) {
    var id = e.detail;
    const {
      regionInfo
    } = this.data;
    let city = [{
      text: "请选择",
      value: 0
    }];
    regionInfo.forEach((item, index) => {
      if (item.id == id) {
        var cities = item.list;
        cities.forEach((c, i) => {
          city.push({
            text: c.name,
            value: c.id
          })
        });
      }
    });
    this.setData({
      cities: city,
      s_city: 0,
      s_province: id
    });
    this.zoneSubmit();
  },
  city_change(e) {
    var cityid = e.detail;
    let zone = [{
      text: "全部",
      value: 0
    }];
    var city = "";
    this.data.regionInfo.forEach((item, index) => {
      if (item.id == parseInt(this.data.s_province)) {
        var cities = item.list;
        cities.forEach((c, i) => {
          if (c.id == parseInt(cityid)) {
            var c_zone = c.list;
            city = c.name.replace('市', '');
            c_zone.forEach((z, j) => {
              zone.push({
                text: z.name,
                value: z.id
              });
            });
          }
        });
      }
    });
    this.setData({
      loadmore: false,
      s_city: cityid,
      zonelist: zone,
      city: city,
      zoneid: 0,
      goodsListPage: 1
    });
    this.zoneSubmit();
    // this.getProductsInfo((res) => {
    //   this.setData({
    //     goodsList: res.list
    //   });
    //   if (this.data.loaddone || res.list.length == 0) {
    //     this.setData({
    //       rec_pageindex: 1,
    //       rec_pages: 0
    //     });
    //     this.getRecShopList((res1) => {
    //       this.setData({
    //         rec_list: res1.list,
    //         rec_loadmore: false,
    //       });
    //     });
    //   }
    // });
  },
  zone_change(e) {
    var zoneid = e.detail;
    var city = this.data.city;
    if (zoneid > 0) {
      this.data.zonelist.forEach((item, index) => {
        if (item.value == zoneid)
          city = item.text.replace('区', '').replace('县', '');
      });
    } else {
      this.data.cities.forEach((item, index) => {
        if (item.value == this.data.s_city)
          city = item.text.replace('市', '');
      });
    }
    this.setData({
      zoneid: zoneid,
      city: city,
      goodsListPage: 1
    });
    this.zoneSubmit();
    // this.getProductsInfo((res) => {
    //   this.setData({
    //     goodsList: res.list
    //   });
    //   if (this.data.loaddone || res.list.length == 0) {
    //     this.setData({
    //       rec_pageindex: 1,
    //       rec_pages: 0
    //     });
    //     this.getRecShopList((res1) => {
    //       this.setData({
    //         rec_list: res1.list,
    //         rec_loadmore: false,
    //       });
    //     });
    //   }
    // });
  },
  handleNotouch() {
    return false
  },
  gocompanydetail(e) {
    const data = e.detail.data;
    if (data.id) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.id,
        distance: data.distance
      });
    }
  },


  mesClick(e) {
    wxApi.navigateTo("/pages/location/index");
  },

  /**
   * 搜索
   */
  visitSearch() {
    wxApi.navigateTo(getPage.search);
  },

  golink(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    //console.log(data.url);
    //转为小写并去除左右空格
    var str = data.url.toLowerCase();
    if (str != "") {
      if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
        wxApi.navigateTo("/pages/web/web?id=" + str);
      } else if (str.indexOf('za://') == 0) {
        //console.log(str);
        var array = str.split('_');
        //console.log(array);
        if (array[0].replace("za://", "") == 'column') {
          app.g_cid = array[1];
          wx.switchTab({
            url: getPage.column
          });
        }
      } else {
        wxApi.navigateTo("/pages/goods/goods?id=" + str);
      }
    }
  },
  /**
   * 禁止手动滑动
   */
  noSwiping() {
    return false;
  },

  /**
   * 获取产品数据
   */
  getProductsInfo(cb, a = false) {
    let {
      goodsNavType,
      goodsListPage,
      goodsListPages,
      loaddone,
      userId,
      s_city,
      zoneid,
      abnor,
      s_province
    } = this.data;
    var mylocation = JSON.parse(wx.getStorageSync('mylocation'));
    http.post(api.default, {
      data: {
        action: 'GetShopList',
        pagesize: 20,
        pageindex: goodsListPage,
        keyword: this.data.keyword,
        latitude: mylocation.latitude,
        longitude: mylocation.longitude,
        userid: userId,
        cityid: s_city,
        zoneid: zoneid,
        provinceid: s_province
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      if (goodsListPage == data.pages) loaddone = true;
      this.setData({
        goodsListPages: data.pages,
        loaddone,
      });
      cb && cb(data);
    });
  },
  getRecShopList(cb, a = false) {
    let {
      rec_pageindex,
      rec_pages,
      rec_loaddone,
      userId,
      s_city,
      zoneid,
      s_province
    } = this.data;
    var mylocation = JSON.parse(wx.getStorageSync('mylocation'));
    http.post(api.default, {
      data: {
        action: 'GetRecShopList',
        pagesize: 20,
        pageindex: rec_pageindex,
        keyword: this.data.keyword,
        latitude: mylocation.latitude,
        longitude: mylocation.longitude,
        userid: userId,
        nocityid: s_city,
        nozoneid: zoneid,
        provinceid: s_province
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      if (rec_pageindex == data.pages) rec_loaddone = true;
      this.setData({
        rec_pages: data.pages,
        rec_loaddone,
      });
      cb && cb(data);
    });
  },
  goHome() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //判断入口是否带参数
    if (options && JSON.stringify(options) !== '{}') {
      this.setData({
        keyword: options.keyword
      });
    }
    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId
      });
    })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    if (this.data.city == "")
      this.setData({
        city: app.globalData.zone.shortname,
      })
    //第一部分数据加载
    http.post(api.default, {
      data: {
        action: 'getadsbanner',
        type: 2
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      //console.log(res.data);
      this.setData({
        swiper: data,
        loading: 1
      });
    });


  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let that = this;
    setTimeout(() => {
      if (that.data.navbarInitHeight == 0) {
        wx.createSelectorQuery().select('.navbar').boundingClientRect(function (rect) {
          if (rect && rect.height > 0) {
            var navbarInitHeight = parseInt(rect.height);
            that.setData({
              navbarInitHeight: navbarInitHeight
            });
          }
        }).exec();
      }
      if (that.data.stkInitHeight == 0) {
        wx.createSelectorQuery().select('.panel_stk').boundingClientRect(function (rect) {
          if (rect && rect.height > 0) {
            var stkInitHeight = parseInt(rect.height);
            that.setData({
              stkInitHeight: stkInitHeight
            });
          }
        }).exec();
      }
    }, 100)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {

    app.getLogin().then(res => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id
      });
      if (app.globalData.zone) {
        this.getRegionInfo().then((res) => {
          //地区格式化
          //this.formatArea();
          let province = [];
          let city1 = [{
            text: "请选择",
            value: 0
          }];
          var zones = [{
            text: "全部",
            value: 0
          }];
          var temp = app.globalData.zone.region_path.substring(1, app.globalData.zone.region_path.length - 1).split(',');
          var s_province = parseInt(temp[0]);
          var s_city = 0;
          if (temp.length >= 2)
            s_city = parseInt(temp[1]);
          var zoneid = 0;
          if (temp.length == 3)
            zoneid = parseInt(temp[2]);
          console.log("onShow位置---------------", res);
          res.forEach((item, index) => {
            province.push({
              text: item.name,
              value: item.id
            })
            if (item.id == s_province) {
              var cities = item.list;
              cities.forEach((c, i) => {
                city1.push({
                  text: c.name,
                  value: c.id
                });
                if (s_city == c.id) {
                  var zonelist = c.list;
                  zonelist.forEach((z, j) => {
                    zones.push({
                      text: z.name,
                      value: z.id
                    })
                  });
                }
              });
            }
          });
          this.setData({
            province: province,
            s_province: s_province,
            cities: city1,
            s_city: s_city,
            zonelist: zones,
            zoneid: zoneid
          });
          // console.log('onShow=========', 's_province=' + s_province + ',s_city=' + s_city + ',zoneid=' + zoneid);
          //加载产品列表
          this.getProductsInfo((res) => {
            //console.log(res)
            this.setData({
              goodsList: res.list,
              loadmore: false,
            });
            if (this.data.loaddone || this.data.goodsListPages == 0) {
              this.getRecShopList((res1) => {
                this.setData({
                  rec_list: res1.list,
                  rec_loadmore: false,
                });
              });
            }
          });
        });
      }

    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      goodsListPage,
      goodsListPages,
      loadmore,
      rec_pageindex,
      rec_pages,
      rec_loadmore
    } = this.data;
    console.log('底部-----');
    //未请求完且未在加载中
    if (goodsListPages > goodsListPage && !loadmore) {
      console.log('底部--------goodsListPages=', goodsListPages);
      console.log('底部------goodsListPage=', goodsListPage);
      console.log('底部-------loadmore=', loadmore);
      goodsListPage++;
      loadmore = true;

      //显示加载效果
      this.setData({
        goodsListPage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.getProductsInfo((res) => {
        let {
          goodsList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          goodsList: goodsList.concat(res.list),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    } else {
      console.log('底部--------rec_pages=', rec_pages);
      console.log('底部------rec_pageindex=', rec_pageindex);
      console.log('底部-------rec_loadmore=', rec_loadmore);
      if (rec_pages > rec_pageindex && !rec_loadmore) {
        rec_pageindex++;
        rec_loadmore = true;

        //显示加载效果
        this.setData({
          rec_pageindex,
          rec_loadmore
        });
        wx.showNavigationBarLoading();

        //请求数据
        this.getRecShopList((res) => {
          let {
            rec_list
          } = this.data;
          rec_loadmore = false;
          this.setData({
            rec_loadmore,
            rec_list: rec_list.concat(res.list),
          });
          //隐藏加载效果
          wx.hideNavigationBarLoading();
        })
      }

    }
  },

  /**
   * 关注店铺
   */
  followClick(event) {
    let {
      isfav,
      ShopId
    } = event.detail;
    var {
      logged,
      userId,
    } = this.data;
    if (logged) {
      if (!isfav) {
        http.post(api.default, {
          data: {
            action: 'fav_shop',
            userid: userId,
            shopid: ShopId,
          }
        }).then((res) => {
          $toast(`收藏成功`, {
            icon: 'success'
          });

          // 前端显示跟新收藏状态
          let goodsArr = this.data.goodsList;
          goodsArr.forEach(item => {
            if (item.ShopId == ShopId) {
              item.isfav = true
            }
          })

          let recArr = this.data.rec_list;
          recArr.forEach(item => {
            if (item.ShopId == ShopId) {
              item.isfav = true
            }
          })
          this.setData({
            rec_list: recArr,
            goodsList: goodsArr
          })
        })
      } else {
        $toast(`已经收藏了哦`, {
          time: 2500
        });
      }
    } else {
      this.goLogin();
    }
  },

  /**
   * 页面滚动函数--监听页面滚动事件
   */
  onPageScroll(e) {
    var that = this;

    wx.createSelectorQuery().select('.pannel_stb').boundingClientRect(function (rect) {
      if (rect && rect.top > 0) {
        // 列表盒子距顶部的高度
        var listInTop = parseInt(rect.top);
        var isSatisfy = (listInTop - that.data.stkInitHeight - that.data.navbarInitHeight) < 0 ? true : false;
        //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
        // if (that.data.isFixedTop === isSatisfy) {
        //   return false;
        // }
        console.log('listInTop,stkInitHeight,navbarInitHeight', listInTop, that.data.stkInitHeight, that.data.navbarInitHeight)
        that.setData({
          isFixedTop: isSatisfy
        });
      }
    }).exec();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        //console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          //console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          //console.log("分享失败");
        }
      }
    }
  }
})